package com.gitee.smsdistribution.common_response.exception;

import com.gitee.smsdistribution.common_response.model.ResultStatus;
import com.gitee.smsdistribution.common_response.error.ErrorResponse;
import com.gitee.smsdistribution.common_response.model.CommonResult;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;

//@ControllerAdvice(assignableTypes = {ExceptionController.class})
@ControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {


    @ExceptionHandler(Exception.class)
    public ResponseEntity<?> handleException(Exception ex, HttpServletRequest request) {
        CommonResult<Object> failure = CommonResult.failure(ResultStatus.INTERNAL_SERVER_ERROR, ex.getMessage());
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(failure);
    }

    // 也可以将 BaseException 换为 RuntimeException
    // 因为 RuntimeException 是 BaseException 的父类
    @ExceptionHandler(BaseException.class)
    public ResponseEntity<?> handleAppException(BaseException ex, HttpServletRequest request) {
        ErrorResponse representation = new ErrorResponse(ex, request.getRequestURI());
        return new ResponseEntity<>(representation, new HttpHeaders(), ex.getError().getHttpStatus());
    }

    @ExceptionHandler(value = ResourceNotFoundException.class)
    public ResponseEntity<?> handleResourceNotFoundException(ResourceNotFoundException ex, HttpServletRequest request) {
        CommonResult<Map<String, Object>> failure = CommonResult.failure(ex.getError(), ex.getData(), ex.getMessage());
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(failure);
    }


    @ExceptionHandler(value = {UnAuthorizedException.class, SendSmsException.class})
    public ResponseEntity<?> handleExceptionWithJsonResponse(BaseException ex, HttpServletRequest request) {
        CommonResult<Map<String, Object>> failure = CommonResult.failure(ex.getError(), ex.getData(), ex.getMessage());
        return ResponseEntity.status(ex.getError().getHttpStatus()).body(failure);
    }
}
